package com.elinkway.infinitemovies.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.elinkway.infinitemovies.bean.AlbumUpdateInfoBean;
import com.elinkway.infinitemovies.bean.Favorite;
import com.elinkway.infinitemovies.utils.MoviesConstant;

import java.util.ArrayList;
import java.util.List;

public class FavoriteDao extends BaseDao<Favorite> {

    private static final String TABLE_NAME = "favorite";
    private static final String FIELD_ID = "id";
    private static final String FIELD_NAME = "name";
    private static final String FIELD_DESC = "desc";
    private static final String FIELD_VT = "vt";
    private static final String FIELD_SRC = "src";
    private static final String FIELD_AID = "aid";
    private static final String FIELD_NOWEPISODES = "nowepisode";
    private static final String FIELD_LATESTEPISODE = "latestepisode";
    private static final String FIELD_ISEND = "isend";
    private static final String FIELD_FAVORITE_TIME = "favorite_time";
    private static final String FIELD_POSTER = "poster";

    public FavoriteDao(Context context) {
        super(context);
    }

    @Override
    public void delete(final String aid) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, aid));
                safelyCloseDataBase();
            }

        });
    }

    @Override
    public void delAll() {

    }

    public List<Favorite> getAll() {
        List<Favorite> list = new ArrayList<Favorite>();
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " order by id DESC", null);
        while (cursor.moveToNext()) {
            Favorite favorite = new Favorite();
            favorite.setAid(cursor.getString(1));
            favorite.setName(cursor.getString(2));
            favorite.setSrc(cursor.getString(5));
            favorite.setDesc(cursor.getString(3));
            favorite.setVt(cursor.getString(4));
            favorite.setNowEpisode(cursor.getString(6));
            favorite.setIsend(cursor.getString(7));
            favorite.setLatestEpisodes(cursor.getString(8));
            favorite.setFavoriteTime(cursor.getLong(9));
            favorite.setPoster(cursor.getString(10));
            list.add(favorite);
        }
        safelyCloseDataBase();
        cursor.close();
        return list;
    }

    public Favorite getByAid(String aid) {
        Favorite favorite = null;
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where aid = '" + aid + "'", null);
        while (cursor.moveToNext()) {
            favorite = new Favorite();
            favorite.setAid(cursor.getString(1));
            favorite.setName(cursor.getString(2));
            favorite.setSrc(cursor.getString(5));
            favorite.setDesc(cursor.getString(3));
            favorite.setVt(cursor.getString(4));
            favorite.setNowEpisode(cursor.getString(6));
            favorite.setIsend(cursor.getString(7));
            favorite.setLatestEpisodes(cursor.getString(8));
            favorite.setFavoriteTime(cursor.getLong(9));
            favorite.setPoster(cursor.getString(10));
        }
        safelyCloseDataBase();
        cursor.close();
        return favorite;
    }

    public void update(final Favorite now) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                ContentValues values = new ContentValues();
                values.put(FIELD_NOWEPISODES, now.getNowEpisodes());
                values.put(FIELD_ISEND, now.getIsend());
                values.put(FIELD_LATESTEPISODE, now.getLatestEpisodes());
                String[] where = {now.getAid()};
                db.update(TABLE_NAME, values, "aid=?", where);
                safelyCloseDataBase();
            }

        });
    }

    public void update(final AlbumUpdateInfoBean now) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                ContentValues values = new ContentValues();
                values.put(FIELD_LATESTEPISODE, now.getNowEpisode());
                values.put(FIELD_ISEND, now.getIsend());
                String[] where = {now.getAid()};
                db.update(TABLE_NAME, values, "aid=?", where);
                safelyCloseDataBase();
            }

        });
    }

    @Override
    public void save(final Favorite bean) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, bean.getAid()));
                Cursor cursor = db.rawQuery(String.format("Select * from %s;", TABLE_NAME), null);
                //收藏夹满时100，删除id最小的，即FIFO
                if (cursor.getCount() == MoviesConstant.FAVORITE_MAXIMUM_SIZE) {
                    db.execSQL("delete from " + TABLE_NAME + " where " + FIELD_ID + "=(select min(" + FIELD_ID + ") from " + TABLE_NAME + ")");
                }
                ContentValues values = new ContentValues();
                values.put(FIELD_AID, bean.getAid());
                values.put(FIELD_NAME, bean.getName());
                values.put(FIELD_SRC, bean.getSrc());
                values.put(FIELD_DESC, bean.getDesc());
                values.put(FIELD_VT, bean.getVt());
                values.put(FIELD_NOWEPISODES, bean.getNowEpisodes());
                values.put(FIELD_ISEND, bean.getIsend());
                values.put(FIELD_FAVORITE_TIME, System.currentTimeMillis());
                values.put(FIELD_POSTER, bean.getPoster());
                db.insert(TABLE_NAME, null, values);
                safelyCloseDataBase();
                cursor.close();
            }
        });
    }

    public boolean isExists(String aid) {
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select " + FIELD_AID + " from " + TABLE_NAME + " where " + FIELD_AID + " = '" + aid + "'", null);
        if (cursor.getCount() == 0) {
            cursor.close();
            safelyCloseDataBase();
            return false;
        } else {
            cursor.close();
            safelyCloseDataBase();
            return true;
        }
    }

    public synchronized List<String> getNoPosterAidList() {
        List<Favorite> list = getAll();
        List<String> aidList = new ArrayList<>();
        for (Favorite favorite : list) {
            if (favorite != null) {
                if (TextUtils.isEmpty(favorite.getPoster())) {
                    aidList.add(favorite.getAid());
                }
            }
        }
        return aidList;
    }

    /**
     * 更新图片，
     *
     * @param now
     */
    public void updatePosters(final AlbumUpdateInfoBean now) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                ContentValues values = new ContentValues();
                values.put(FIELD_POSTER, now.getPoster());
                String[] where = {now.getAid()};
                db.update(TABLE_NAME, values, "aid=?", where);
                safelyCloseDataBase();
            }

        });
    }

}
